package org.geometerplus.fbreader.library;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.image.ZLImage;
import org.geometerplus.zlibrary.core.image.ZLLoadableImage;
import org.zixuanstudio.ebook.R;
import org.geometerplus.zlibrary.ui.android.image.ZLAndroidImageData;
import org.geometerplus.zlibrary.ui.android.image.ZLAndroidImageManager;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;

public class SyncImageLoader {

	private Object lock = new Object();
	
	private boolean mAllowLoad = true;
	
	private boolean firstLoad = true;
	
	private int mStartLoadLimit = 0;
	
	private int mStopLoadLimit = 0;
	
	final Handler handler = new Handler();
	
	private HashMap<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();   
	
	//private ArrayList<SoftReference<Bitmap>>  mBitmapCache = new ArrayList<SoftReference<Bitmap>>();
	private HashMap<String, SoftReference<Bitmap>> mBitmapCache = new HashMap<String, SoftReference<Bitmap>>();   
	
	private static SyncImageLoader  mInstance = null;
	
	public static SyncImageLoader getInstance() {
		if (mInstance == null) {
			return new SyncImageLoader();
		}
		return mInstance;
		
	}
	
	private SyncImageLoader() {
		
	}
	public interface OnImageLoadListener {
		public void onImageLoad(Integer t, Drawable drawable);
		public void onError(Integer t);
	}
	
	public void setLoadLimit(int startLoadLimit,int stopLoadLimit){
		if(startLoadLimit > stopLoadLimit){
			return;
		}
		mStartLoadLimit = startLoadLimit;
		mStopLoadLimit = stopLoadLimit;
	}
	
	public void restore(){
		mAllowLoad = true;
		firstLoad = true;
	}
		
	public void lock(){
		mAllowLoad = false;
		firstLoad = false;
	}
	
	public void unlock(){
		mAllowLoad = true;
		synchronized (lock) {
			lock.notifyAll();
		}
	}

	public void loadImage(Integer t, String imageUrl,
			OnImageLoadListener listener) {
		final OnImageLoadListener mListener = listener;
		final String mImageUrl = imageUrl;
		final Integer mt = t;
		
		new Thread(new Runnable() {

			@Override
			public void run() {
				if(!mAllowLoad){
					//DebugUtil.debug("prepare to load");
					synchronized (lock) {
						try {
							lock.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				
				if(mAllowLoad && firstLoad){
					loadImage(mImageUrl, mt, mListener);
				}
				
				if(mAllowLoad && mt <= mStopLoadLimit && mt >= mStartLoadLimit){
					loadImage(mImageUrl, mt, mListener);
				}
			}

		}).start();
	}
	
	private void loadImage(final String mImageUrl,final Integer mt,final OnImageLoadListener mListener){
		
		if (imageCache.containsKey(mImageUrl)) {  
            SoftReference<Drawable> softReference = imageCache.get(mImageUrl);  
            final Drawable d = softReference.get();  
            if (d != null) {  
            	handler.post(new Runnable() {
    				@Override
    				public void run() {
    					if(mAllowLoad){
    						mListener.onImageLoad(mt, d);
    					}
    				}
    			});
                return;  
            }  
        }  
		try {
			final Drawable d = loadImageFromUrl(mImageUrl);
			if(d != null){
                imageCache.put(mImageUrl, new SoftReference<Drawable>(d));
			}
			handler.post(new Runnable() {
				@Override
				public void run() {
					if(mAllowLoad){
						mListener.onImageLoad(mt, d);
					}
				}
			});
		} catch (IOException e) {
			handler.post(new Runnable() {
				@Override
				public void run() {
					mListener.onError(mt);
				}
			});
			e.printStackTrace();
		}
	}

	public static Drawable loadImageFromUrl(String path) throws IOException {
		ZLFile zlFile = ZLFile.createFileByPath(path);
		ZLImage bookImage = Library.getCover(zlFile);
		final Book book = Book.getByFile(zlFile);
		if (bookImage instanceof ZLLoadableImage) {
			final ZLLoadableImage loadableImage = (ZLLoadableImage) bookImage;
			if (!loadableImage.isSynchronized()) {
				loadableImage.synchronize();
			}
		}
		final ZLAndroidImageData data = ((ZLAndroidImageManager) ZLAndroidImageManager
				.Instance()).getImageData(bookImage);
		Bitmap cover = data.getBitmap(106, 151);
		BitmapDrawable drawable = null;
		if (cover != null) {
			 drawable = new BitmapDrawable(cover);
		}
		
		return drawable;
	}
	

	public  Bitmap loadImageFromPath(String path) throws IOException {
		ZLFile zlFile = ZLFile.createFileByPath(path);
		ZLImage bookImage = Library.getCover(zlFile);
		final Book book = Book.getByFile(zlFile);
		if (bookImage instanceof ZLLoadableImage) {
			final ZLLoadableImage loadableImage = (ZLLoadableImage) bookImage;
			if (!loadableImage.isSynchronized()) {
				loadableImage.synchronize();
			}
		}
		final ZLAndroidImageData data = ((ZLAndroidImageManager) ZLAndroidImageManager
				.Instance()).getImageData(bookImage);
		Bitmap cover = data.getBitmap(106, 151);
		
		return cover;
	}
	
	public  void createImageCache() throws IOException {
		for (Book book:ImageUtil.mBooks) {
			String path = book.File.getPath();
			if (mBitmapCache.get(path) == null) {
				Bitmap bm = loadImageFromPath(path);
				if (bm != null) {
					mBitmapCache.put(path, new SoftReference<Bitmap>(bm));
				}
			}
		}
	}
	
	public Bitmap getCoverFromCache(String path)  {
		
		if (mBitmapCache.get(path) != null) {
			return mBitmapCache.get(path).get();
		} else {
			Bitmap bm = null;
			try {
				bm = loadImageFromPath(path);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (bm != null) {
				mBitmapCache.put(path, new SoftReference<Bitmap>(bm));
				return bm;
			}
		}
		return null;
		
	}
}
